<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="/js/gmaps.js"></script>

<script type="text/javascript" language="javascript">

var updateTimeOut;

function resizeMap() {
 $('#map').css({'height':(($(document).height())-40)+'px', 'width':'100%'});
 return false;
}

function checkMarkerExists(temp_id) {
  for (var i=0, marker; marker=map.markers[i]; i++){
   if (marker.temp_id==temp_id) return true;
  }
  return false;
}

function getMarkerIndex(temp_id) {
  for (var i=0, marker; marker=map.markers[i]; i++){
   if (marker.temp_id==temp_id) return i;
  }
 return false;
}

function updateLocations() {
 var url="?";
 url+='&ajax=1&op=getlocations';

 $.ajax({
   url: url
  }).done(function(data) { 
   var obj=jQuery.parseJSON(data);
   if (obj.LOCATIONS.length>0) {
    var locations=obj.LOCATIONS;
    for(var i=0;i<locations.length;i++) {
     var location=locations[i];
     var temp_id=location.ID;
     //alert(location);
     map.drawCircle({
      temp_id:temp_id,
       lat: location.LAT,
       lng: location.LON,
       title: location.TITLE,
       radius: parseFloat(location.RANGE),
       clickable: false,
     });//       radius: location.RANGE,
     /*
     map.addMarker({
       temp_id:temp_id,
       lat: location.LAT,
       lng: location.LON,
       title: location.TITLE,
      });
     */
    }
   }
  });


 return false;
}

function updateRoute(device_id, color) {
 var url="?";
 url+='&ajax=1&op=getroute&period=[#PERIOD#]&from=[#FROM#]&to=[#TO#]&device_id='+device_id;

 $.ajax({
   url: url
  }).done(function(data) { 
   var obj=jQuery.parseJSON(data);
   if (obj.PATH.length>0) {


    var path=obj.PATH;
    var points=obj.POINTS;

    map.drawPolyline({
     path: path,
     strokeColor: color,
     strokeOpacity: 0.3,
     strokeWeight: 4
    });
    
/*
   var wps=new Array();
   for(var i=0;i<points.length-1;i++) {
    var point = new google.maps.LatLng(points[i].LAT,points[i].LON);
    //var point =1;
    wps.push({location:point});

   }

map.drawRoute({
  origin: [obj.FIRST_POINT.LAT, obj.FIRST_POINT.LON],
  destination: [obj.LAST_POINT.LAT, obj.LAST_POINT.LON],
  waypoints: wps,
  travelMode: 'driving',
  strokeColor: color,
  strokeOpacity: 0.6,
  strokeWeight: 6
});
*/





    for(var i=0;i<points.length;i++) {
     var point=points[i];
     var temp_id=point.ID;
     map.addMarker({
       temp_id:temp_id,
       lat: point.LAT,
       lng: point.LON,
       title: point.TITLE,
       icon: 'http://labs.google.com/ridefinder/images/mm_20_'+color+'.png',
      });
    }
    map.fitZoom();
   }
  });
 return false;
}


function updateMarkers() {
 var url="?";
 url+='&ajax=1&op=getmarkers';
 $.ajax({
   url: url
  }).done(function(data) { 
   var obj=jQuery.parseJSON(data);
   var markers=obj.MARKERS;

   for(var i=0;i<markers.length;i++) {
     var marker=markers[i];
     var temp_id=marker.ID;
     if (!checkMarkerExists(temp_id)) {


     map.addMarker({
       temp_id:temp_id,
       lat: marker.LAT,
       lng: marker.LON,
       title: marker.NAME,
       icon: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/'+marker.COLOR+'-dot.png',
       infoWindow: {
        content: marker.HTML
       },
      });

     } else {

      mk=getMarkerIndex(temp_id);
      var marker_obj=map.markers[mk];
      var lat = parseFloat(marker.LAT);
      var lng = parseFloat(marker.LON);
      var oldLatLng = marker_obj.getPosition();
      var newLatLng = new google.maps.LatLng(lat, lng);
      marker_obj.setPosition(newLatLng);

      if ((oldLatLng.lng()!=newLatLng.lng()) || (oldLatLng.lat()!=newLatLng.lat())) {
       // marker moved
       map.setCenter(newLatLng.lat(), newLatLng.lng());
      }

     }
   }
   updateTimeOut=setTimeout('updateMarkers();', 3000);

  });
 return false;
}



    var map;


    [#if LATEST_LAT!=""#]
    var startLat=[#LATEST_LAT#];
    [#else#]
    var startLat=53.901506;
    [#endif#]

    [#if LATEST_LON!=""#]
    var startLon=[#LATEST_LON#];
    [#else#]
    var startLon=27.565269;
    [#endif#]
    
    $(document).ready(function(){
      map = new GMaps({
        div: '#map',
        lat: startLat,
        lng: startLon,
        zoom: 18,
      });


[#if LATEST_LAT=""#]
GMaps.geolocate({
  success: function(position) {
    map.setCenter(position.coords.latitude, position.coords.longitude, function() {centerChanged();});
  },
  error: function(error) {
    //alert('Geolocation failed: '+error.message);
  },
  not_supported: function() {
    //alert("Your browser does not support geolocation");
  },
  always: function() {
    //alert("Done!");
  }
});
[#endif#]

updateMarkers();
resizeMap();

[#begin DEVICES#]
 updateRoute([#ID#], '[#COLOR#]');
[#end DEVICES#]
updateLocations();
//
    });


function legendClicked(id, color) {
 map.removePolylines();
 map.removeOverlays();
 map.removeMarkers();
 updateRoute(id, color);
 return false;
}

</script>

<div id="add_controls">
&nbsp;
<table border="0" cellspacing=0 cellpadding=2>
 <tr>
 [#begin DEVICES#]
  <td>
  <img src="http://labs.google.com/ridefinder/images/mm_20_[#COLOR#].png" border="0">
  </td>
  <td>
  <a href="#" onClick="return legendClicked([#ID#], '[#COLOR#]');">[#NAME#] ([#TITLE#])</a>
  <!--#
  [#if LATEST_LAT!=""#]map.setCenter([#LATEST_LAT#], [#LATEST_LON#]);[#endif#]
  #-->
  </td>
 [#end DEVICES#]
 <form action="?" method="get">
 <td valign="top">
 <script language="javascript">
  function periodUpdated() {
   if ($('#selPeriod').val()=='custom') {
    $('#customDates').show();
   } else {
    $('#customDates').hide();
   }
   return false;
  }
 </script>
 <#LANG_PERIOD#>:
 <select name="period" onChange='periodUpdated();' id='selPeriod'>
  <option value="today"[#if PERIOD="today"#] selected[#endif#]><#LANG_PERIOD_TODAY#>
  <option value="day"[#if PERIOD="day"#] selected[#endif#]><#LANG_PERIOD_DAY#>
  <option value="week"[#if PERIOD="week"#] selected[#endif#]><#LANG_PERIOD_WEEK#>
  <option value="month"[#if PERIOD="month"#] selected[#endif#]><#LANG_PERIOD_MONTH#>
  <option value="custom"[#if PERIOD="custom"#] selected[#endif#]><#LANG_PERIOD_CUSTOM#>...
 </select>
 <span id='customDates' [#if PERIOD!="custom"#]style="display:none"[#endif#]>
 &nbsp;&nbsp;&nbsp;
 (YYYY-MM-DD)
 <input type="text" name="from" value="[#FROM#]">
 -
 <input type="text" name="to" value="[#TO#]">
 </span>
 <input type="submit" name="Update" value="<#LANG_SEARCH#>">
 </td>
 </form>
 </tr>
</table>
</div>

<div id="map" style="width: 100%; height: 620px;"></div>